import React from 'react';
import { Spin } from 'antd';
import { useRequest } from 'ahooks';
import { connect } from 'dva';
import MapContainer from '@/components/MapContainer';
import MaskLoad from '@/components/MarketingMap/MaskLoad';
import Sidebar from '@/components/MarketingMap/Sidebar';
import TopFilterForm from '@/components/MarketingMap/TopFilterForm';
import useForm from '@/components/MarketingMap/TopFilterForm/useForm';
import usePermissionCheck from '@/hooks/usePermissionCheck';
import { fetchInflowStore } from '@/services/marketingMap/inflowAnalysis';
import OverallContext from '../context';
import StatisticsOverview from './StatisticsOverview';
import UserProfile from './UserProfile';
import useMap from './useMap';
import styles from '../styles/index.less';

const InflowAnalysis: React.FC<any> = ({ form, isAuth }) => {
  const { loading: isLoading, options, initialValue, query, date, codeNameMap, onSubmit } = form;

  const { data, run, loading } = useRequest(() => fetchInflowStore(query), {
    refreshDeps: [query],
    refreshDepsAction: () => {
      if (!query.store) {
        return;
      }
      run();
    },
  });

  const { onRenderingCompleted } = useMap(data?.flowData, isAuth);

  const provider = {
    query,
    codeNameMap,
    date,
    onSubmit,
  };

  return (
    <OverallContext.Provider value={provider}>
      <div className={styles.wrapper}>
        <div className={styles.top_wrap}>
          <TopFilterForm
            defaultValue={initialValue}
            value={query}
            onSubmit={onSubmit}
            options={options || {}}
            auth="inflow-screen"
          />
        </div>
        <Sidebar
          items={[
            {
              key: '1',
              label: '统计概况',
              children: (
                <StatisticsOverview rankData={data?.rankData} overviewData={data?.overviewData} />
              ),
            },
            { key: '2', label: '流入用户画像', children: <UserProfile /> },
          ]}
        />
        {(loading || isLoading) && <MaskLoad />}

        <MapContainer loca onRenderingCompleted={onRenderingCompleted} />
      </div>
    </OverallContext.Provider>
  );
};

export default connect(({ menu, loading }: any) => ({
  permissions: menu.permissions,
  loading: loading.models.menu,
}))(({ permissions, loading }: any) => {
  const [isAuth] = usePermissionCheck(permissions, 'inflow-screen');
  const form = useForm(isAuth, loading);

  return form.state ? (
    <div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
      <Spin />
    </div>
  ) : (
    <InflowAnalysis form={form} isAuth={isAuth} />
  );
});
